package com.xckj.cycling.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.facebook.login.LoginResult
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.junca.android.service.Request
import com.xckj.cycling.bean.UserInfoResponseBean
import com.xckj.cycling.bean.UserinfoBean
import com.xckj.cycling.framework.model.Response
import com.xckj.cycling.model.UnreadModel
import com.xckj.cycling.model.UploadResultModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.io.File

class LoginViewModel : ViewModel() {
    private val lastJob: MutableList<Job> = mutableListOf()
    val userLiveData = MutableLiveData<UserinfoBean?>()

    val userCenterLiveData = MutableLiveData<UserInfoResponseBean>()
    val unreadLiveData = MutableLiveData<UnreadModel>()
    fun loginByGoogle(
        googleAccount: GoogleSignInAccount,
        callback: suspend (Response<UserInfoResponseBean>) -> Unit
    ) {
        viewModelScope.launch {
            val r = Request.postSuspend<UserInfoResponseBean>(
                "qixing/user/third",
                HashMap<String, Any>().apply {
                    put("platform", "google")
                    put("token", googleAccount.idToken.toString())
                })
            if (r.isSuccessful) {
                r.data?.userinfo?.isNew= r.data?.isNew!!
                userLiveData.value = r.data?.userinfo
            }
            callback.invoke(r)
        }
    }

    fun loginByFacebook(
        loginResult: LoginResult,
        callback: suspend (Response<UserInfoResponseBean>) -> Unit
    ) {
        viewModelScope.launch {
            val r = Request.postSuspend<UserInfoResponseBean>(
                "qixing/user/third",
                HashMap<String, Any>().apply {
                    put("platform", "facebook")
                    put("token", loginResult.accessToken.token)
                })
            if (r.isSuccessful) {
                r.data?.userinfo?.isNew= r.data?.isNew!!
                userLiveData.value = r.data?.userinfo
            }
            callback.invoke(r)
        }
    }


    fun loadUserCenter() {
        viewModelScope.launch {
            val r = loadUserCenterFromServer()
            if (r.isSuccessful) {
                userCenterLiveData.value = r.data
            }
        }
    }

    fun userCenterHeartBeat(): Job {
        return viewModelScope.launch {
            eid = null
            while (isActive) {
                val r = loadUserCenterFromServer()
                if (r.isSuccessful) {
                    userCenterLiveData.value = r.data
                }
                delay(5000)
            }
        }.apply {
            lastJob.add(this)
        }
    }

    fun unreadHeartBeat() {
        viewModelScope.launch {
            while (isActive) {
                val r = Request.postSuspend<UnreadModel>(
                    "msg/notice",
                    HashMap<String, Any>().apply {
                    })
                if (r.isSuccessful) {
                    unreadLiveData.value = r.data
                }
                delay(10000)
            }
        }.apply {
            lastJob.add(this)
        }
    }

    private suspend fun loadUserCenterFromServer(): Response<UserInfoResponseBean> {
        return Request.postSuspend<UserInfoResponseBean>(
            "qixing/user/center",
            HashMap<String, Any>().apply {
                eid?.let {
                    put("eid", it)
                }
            })
    }

    fun uploadAvatar(path: String, callback: suspend (Response<UploadResultModel>) -> Unit) {
        viewModelScope.launch {
            val r = Request.postWithFile<UploadResultModel>(
                "qixing/user/uploadavatar",
                HashMap<String, File>().apply {
                    put("file", File(path))
                })
            userCenterLiveData.value = userCenterLiveData.value?.let {
                it.userinfo?.avatar = r.data?.fullurl
                it
            }
            callback.invoke(r)
        }
    }

    fun uploadImage(file: File, callback: suspend (Response<UploadResultModel>) -> Unit) {
        viewModelScope.launch {
            val r = Request.postWithFile<UploadResultModel>(
                "qixing/cycling/uploadimg",
                HashMap<String, File>().apply {
                    put("file", file)
                })
            callback.invoke(r)
        }
    }

    fun agreeTryRide(id: Int, callback: (Response<Any>) -> Unit) {
        viewModelScope.launch {
            val r = Request.getSuspend<Any>(
                "qixing/cycling/acceptTryride",
                HashMap<String, Any>().apply {
                    put("id", id)
                })
            callback.invoke(r)
            loadUserCenter()
        }
    }

    fun refuseTryRide(id: Int, callback: (Response<Any>) -> Unit) {
        viewModelScope.launch {
            val r = Request.getSuspend<Any>(
                "qixing/cycling/refusedTryride",
                HashMap<String, Any>().apply {
                    put("id", id)
                })
            callback.invoke(r)
            loadUserCenter()
        }
    }

    fun endTryRide(id: Int, callback: (Response<Any>) -> Unit) {
        viewModelScope.launch {
            val r = Request.getSuspend<Any>(
                "qixing/cycling/endTryride",
                HashMap<String, Any>().apply {
                    put("id", id)
                })
            callback.invoke(r)
            loadUserCenter()
        }
    }

    fun commentTryRide(id: String, content: String, callback: (Response<Any>) -> Unit) {
        viewModelScope.launch {
            val r = Request.getSuspend<Any>(
                "qixing/cycling/tryrideEvaluation",
                HashMap<String, Any>().apply {
                    put("id", id)
                    put("str", content)
                })
            callback.invoke(r)
            loadUserCenter()
        }
    }

    fun logout() {
        userLiveData.value = null
        userCenterLiveData.value = null
        lastJob.forEach {
            it.cancel()
        }
        unreadLiveData.value = null
        lastJob.clear()
    }

    private var eid: String? = null
    fun setEid(id: String) {
        eid = id
    }

    fun updateTryRide(b: Boolean, callback: (Response<Any>) -> Unit) {
        viewModelScope.launch {
            val r = Request.postSuspend<Any>(
                "qixing/user/profile",
                HashMap<String, Any>().apply {
                    put("tryride", if (b) 1 else 0)
                })
            callback.invoke(r)
        }
    }


    fun updateHasCar(hasCar:Boolean,callback: (Response<Any>) -> Unit){
        viewModelScope.launch {
            val r = Request.postSuspend<Any>(
                "qixing/user/profile",
                HashMap<String, Any>().apply {
                    put("bikestatus", if (hasCar) 1 else 0)
                })
            callback.invoke(r)
        }
    }


}